//
//  LFBReadViewController.m
//  ONE
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 GroupNine. All rights reserved.
//

#import "LFBReadViewController.h"
#import "LFBNetTool.h"
#import <SDCycleScrollView.h>
#import "LFBReadCarouselModel.h"
#import "LFBReadTypeModel.h"
#import "LFBReadBaseView.h"
#import "LFBReadDetailViewController.h"
#import "LFBReadTopTenArticleViewController.h"
#import "LFBReadPreviousViewController.h"

@interface LFBReadViewController () <GMCPagingScrollViewDelegate, GMCPagingScrollViewDataSource>
{
    AAPullToRefresh *pullToRefreshLeft;
    AAPullToRefresh *pullToRefreshRight;
}

/** 头部轮播图 */
@property (nonatomic, strong) SDCycleScrollView *carouselView;

/** 底部翻页滚动视图 */
@property (nonatomic, strong) GMCPagingScrollView *pagingScrollView;

@end

@implementation LFBReadViewController
{
    // 轮播图数据源数组
    NSArray *carousels;
    // 轮播图图片数组
    NSMutableArray *carouselCovers;
    // 文章类型
    LFBReadTypeModel *readType;
}

- (void)dealloc
{
    pullToRefreshLeft.showPullToRefresh = NO;
    pullToRefreshRight.showPullToRefresh = NO;
    
    _pagingScrollView.delegate = nil;
    _pagingScrollView.dataSource = nil;
}

+ (UINavigationController *)defaultReadNavigationController
{
    static UINavigationController *nav = nil;
    // 单例
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        LFBReadViewController *readVC = [[LFBReadViewController alloc] init];
        nav = [[UINavigationController alloc] initWithRootViewController:readVC];
    });
    return nav;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"阅读";
    
    [self addNavigationBarLeftSearchItem];
    [self addNavigationBarRightMeItem];
    
    [self initData];
    [self createReadView];
    [self loadCache];
    [self getCarouselData];
    [self getTypeData];
}

#pragma mark --初始化数据
- (void)initData
{
    carouselCovers = @[].mutableCopy;
}

#pragma mark --创建阅读首页
- (void)createReadView
{
    __weak typeof(self) weakSelf = self;
    
    _carouselView = [SDCycleScrollView new];
    _carouselView.backgroundColor = [UIColor colorWithRed:0.72 green:0.72 blue:0.72 alpha:1.00];
    _carouselView.placeholderImage = [UIImage imageNamed:@"top10"];
    _carouselView.autoScrollTimeInterval = 5;
    // 监听点击事件
    _carouselView.clickItemOperationBlock = ^(NSInteger currentIndex)
    {
        [weakSelf showTopTenArticleWithIndex:currentIndex];
    };
    [self.view addSubview:_carouselView];
    [_carouselView makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.equalTo(143.5);
    }];
    
    _pagingScrollView = [GMCPagingScrollView new];
    _pagingScrollView.backgroundColor = LYLViewControllerBGColor;
    [_pagingScrollView registerClass:[LFBReadBaseView class] forReuseIdentifier:kLFBReadBaseViewID];
    _pagingScrollView.delegate = self;
    _pagingScrollView.dataSource = self;
    _pagingScrollView.pageInsets = UIEdgeInsetsZero;
    _pagingScrollView.interpageSpacing = 0;
    
    pullToRefreshLeft = [_pagingScrollView.scrollView addPullToRefreshPosition:AAPullToRefreshPositionLeft actionHandler:^(AAPullToRefresh *v) {
        [weakSelf refreshReadIndex];
        [v performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
    }];
    // 临界值
    pullToRefreshLeft.threshold = 100;
    pullToRefreshLeft.borderColor = LYLAppThemeColor;
    pullToRefreshLeft.borderWidth = 4;
    pullToRefreshLeft.imageIcon = [UIImage new];
    
    pullToRefreshRight = [_pagingScrollView.scrollView addPullToRefreshPosition:AAPullToRefreshPositionRight actionHandler:^(AAPullToRefresh *v) {
        [weakSelf loadMoreReadIndex];
        [v performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
    }];
    pullToRefreshRight.borderColor = LYLAppThemeColor;
    pullToRefreshRight.borderWidth = 4;
    pullToRefreshRight.imageIcon = [UIImage new];
    
    [self.view addSubview:_pagingScrollView];
    [_pagingScrollView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_carouselView.bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
    _pagingScrollView.hidden = YES;
}

- (void)loadCache
{
//    id cacheCarousels = [NSKeyedUnarchiver unarchiveObjectWithFile:LYLCacheReadCarouselFilePath];
    
}

#pragma mark --设置轮播图数据源数组
- (void)setupCarouselViewDataSource
{
    [carouselCovers removeAllObjects];
    
    for (LFBReadCarouselModel *model in carousels) {
        [carouselCovers addObject: model.cover];
    }
    
    _carouselView.imageURLStringsGroup = carouselCovers;
}

#pragma mark --刷新阅读页面
- (void)refreshReadIndex
{
    [_pagingScrollView setCurrentPageIndex:0 reloadData:NO];
}

#pragma mark --加载更多阅读页面
#warning 跳转往期列表!!!!!!!!
- (void)loadMoreReadIndex
{
    [_pagingScrollView setCurrentPageIndex:([self numberOfMaxIndex] - 1) reloadData:NO];
    // 显示往期列表
    
    
}

#pragma mark --跳转文章详情页面
- (void)openReadDetailViewControllerWithReadType:(LYLReadType)type
{
    LFBReadDetailViewController *readDVC = [[LFBReadDetailViewController alloc] init];
    readDVC.dataSource = type == LYLReadTypeShort ? readType.essay : (type == LYLReadTypeSerial ? readType.serial : readType.question);
    [self.navigationController pushViewController:readDVC animated:YES];
}

#pragma mark --阅读页最大下标
- (NSInteger)numberOfMaxIndex
{
    return MAX(MAX(readType.essay.count, readType.serial.count), readType.question.count);
}

#pragma mark --跳转轮播图内容页面
- (void)showTopTenArticleWithIndex:(NSInteger)index
{
    LFBReadTopTenArticleViewController *topTenAVC = [[LFBReadTopTenArticleViewController alloc] init];
    topTenAVC.carouseModel = carousels[index];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topTenAVC];
    [self presentViewController:nav animated:NO completion:NULL];
}

#pragma mark --GMCPagingScrollViewDataSource
- (NSUInteger)numberOfPagesInPagingScrollView:(GMCPagingScrollView *)pagingScrollView
{
    return [self numberOfMaxIndex];
}

- (UIView *)pagingScrollView:(GMCPagingScrollView *)pagingScrollView pageForIndex:(NSUInteger)index
{
    LFBReadBaseView *view = [pagingScrollView dequeueReusablePageWithIdentifier:kLFBReadBaseViewID];
    [view configureViewWithReadEssay:readType.essay[index] readSerial:readType.serial[index] readQuestion:readType.question[index] atIndex:index inViewController:self];
    __weak typeof(self) weakSelf = self;
    view.readSelected = ^(LYLReadType type)
    {
        [weakSelf openReadDetailViewControllerWithReadType:type];
    };
    
    return view;
}      

#pragma mark --GMCPagingScrollViewDelegate
- (void)pagingScrollViewDidScroll:(GMCPagingScrollView *)pagingScrollView
{
    if (_pagingScrollView.isDragging) {
        CGPoint contentOffset = pagingScrollView.scrollView.contentOffset;
        pagingScrollView.scrollView.contentOffset = CGPointMake(contentOffset.x, 0);
    }
}

#pragma mark --网络请求
- (void)getCarouselData
{
    [LFBNetTool getNetWithURL:LYLApiReadingCarousel Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        if ([result[@"res"] integerValue] == 0) {
            NSArray *data = result[@"data"];
            NSMutableArray *datas = [NSMutableArray array];
            for (NSDictionary *dic in data) {
                LFBReadCarouselModel *carouselModel = [[LFBReadCarouselModel alloc] initWithDic:dic];
                [datas addObject:carouselModel];
            }
            carousels = datas.copy;
            [self setupCarouselViewDataSource];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                [NSKeyedArchiver archiveRootObject:carousels toFile:LYLCacheReadCarouselFilePath];
            });
        }
    } Failure:^(NSError *error) {
        
    }];
}

#pragma mark --获得文章类型数据
- (void)getTypeData
{
    [LFBNetTool getNetWithURL:LYLApiReadingIndex Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        if ([result[@"res"] integerValue]  == 0) {
            NSDictionary *data = result[@"data"];
            LFBReadTypeModel *typeModel = [[LFBReadTypeModel alloc] initWithDic:data];
            readType = typeModel;
        
            _pagingScrollView.hidden = NO;
            [_pagingScrollView reloadData];
            // 防止加载出来前用户滑动而跳转到了最后一个
            [_pagingScrollView setCurrentPageIndex:0];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                [NSKeyedArchiver archiveRootObject:readType toFile:LYLCacheReadIndexFilePath];
            });
        }
    } Failure:^(NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
